<?php
namespace app\admin\controller;

use app\admin\model\EducationModel;
use app\admin\model\TeacherModel;
use app\admin\model\StudentModel;
use app\admin\model\DepartmentModel;
use app\admin\model\StRollOutModel;
use app\admin\model\ProductModel;
use think\Request;
use think\Db;
use app\admin\controller\Finance;
class Education extends Base
{
    /**
     * 教务管理
     */
    public function _initialize(){
        $this->teacherModel = new TeacherModel();
		$this->studentModel = new StudentModel();
        parent::_initialize();
    }

    #----------------------------------------------< 教务老师管理 >----------------------------------------------#
    /**
     * [教务老师列表]
     */
    public function teacher (){
        if(request()->isAjax()){
            $param = input('param.');
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $whereOr = $this->seaWhereOr($param);
            $where = $this->seaWhere($param);
            $return['rows'] = $this->teacherModel->getInfoByWhere($where,$whereOr,true,$offset,$limit);
            $whereOr = $this->seaWhereOr($param);
            $where = $this->seaWhere($param);
            $return['total'] = $this->teacherModel->getInfoByWhere($where,$whereOr);
            $return['rows'] = $this->replenishTeacherInfo($return['rows']);
            return $return;
        }
        $schools = DB::name('school_specialty')->where('pid',0)->select();
        $this->assign([
            'schools' => $schools
        ]);
        return $this->fetch();
    }
    /**
     * [添加教务老师]
     */
    public function addTeacher(){
        $param = input('post.');
		if(!isset($param['school_id'])){
			return ['code'=>0,'msg'=>'请至少选择一个学校'];
		}
		$param = $this->translateSchool_id($param);
        $param['create_uid'] = session('id');
        return $this->teacherModel->addTeacher($param);
    }
    /**
     * [编辑教务老师]
     */
    public function editTeacher(){
        $param = input('post.');
		if(!isset($param['school_id'])){
			return ['code'=>0,'msg'=>'请至少选择一个学校'];
		}
        $param = $this->translateSchool_id($param);
        return $this->teacherModel->editTeacher($param);
    }
    /**
     * [删除教务老师]
     */
    public function delTeacher(){
        $param = input('post.');
        $ids = explode(',',$param['ids']);
        return $this->teacherModel->delTeacher($ids);
    }
    /**
     * [清除教务老师登录账号]
     */
    public function delTeacherUser(){
        $param = input('post.');
        $id = $param['id'];
        return $this->teacherModel->delTeacherUser($id);
    }
    #----------------------------------------------< 学生管理 >----------------------------------------------#
    /**
     * [学生管理]
     */
    public function student (){
		new Finance();
		if(request()->isAjax()){
            $param = input('param.');
			$param['seaName'] ? $whereName=['name'=>['like','%'.$param['seaName'].'%']] : $whereName = [];
			$param['seaPhone'] ? $wherePhone=['phone'=>['like','%'.$param['seaPhone'].'%']] : $wherePhone = [];
			$param['seaSchool'] ? $whereSchool=['school_id'=>$param['seaSchool']] : $whereSchool = [];
			$param['seaMajor'] ? $whereMajor=['major_id'=>$param['seaMajor']] : $whereMajor = [];
			$param['seaBatch'] ? $whereBatch=['batch'=>['like','%'.$param['seaBatch'].'%']] : $whereBatch = [];
			// $param['seaClass'] ? $whereClass=['class'=>['like','%'.$param['seaClass'].'%']] : $whereClass = [];
			$whereClass = [];
			($param['seaSchoolRoll']!='') ? $whereSchoolRoll=['school_roll'=>$param['seaSchoolRoll']] : $whereSchoolRoll = [];
			($param['seaRollStatus']!='') ? $whereRollStatus=['roll_status'=>$param['seaRollStatus']] : $whereRollStatus = [];
			$where = ['delete_status'=>0,'school_roll'=>['<>',0]];
			if($param['seaAsker'] != ''){
				$where['consultant'] = $param['seaAsker'];
			}elseif($param['seaAsk_D'] != ''){
				$role = DB::name('role')->where('department_id',$param['seaAsk_D'])->column('id');
				$user = DB::name('user')->where(['role_id'=>['in',$role]])->column('id');
				$where['consultant'] = ['in',$user];
			}
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $return['rows'] = $this->studentModel->getInfoByWhere(
				$where,$whereName,$wherePhone,$whereSchool,$whereMajor,$whereBatch,$whereClass,$whereSchoolRoll,$whereRollStatus,
				true,$offset,$limit
			);
            $return['total'] = $this->studentModel->getInfoByWhere(
				$where,$whereName,$wherePhone,$whereSchool,$whereMajor,$whereBatch,$whereClass,$whereSchoolRoll,$whereRollStatus
			);
			$return['rows'] = $this->translateStudent($return['rows']);
            return $return;
        }
        $schools = DB::name('school_specialty')->where('pid',0)->select();
		$rollStatus = DB::name('roll_status_name')->where('is_abnormal',0)->order('id desc')->select();
		$StRollOutMd = new StRollOutModel();
		$StRollOutInfo = $StRollOutMd->getInfoByWhere();
		$proModel = new ProductModel();
        $this->assign([
            'schools' => $schools,
			'rollStatus' => $rollStatus,
			'StRollOutInfo' => $StRollOutInfo,
			'CanseeSchool' => $proModel->getCanseeSchool()
        ]);
        return $this->fetch();
    }
	/**
	 * [学员信息详情]
	 */
	public function showSTInfo(){
		$st_id = input('get.st_id');
		$where = [
			'delete_status' => 0,
			'id' => $st_id
		];
		$stInfo = $this->studentModel->getInfoByWhere($where,'','','','','','','','',true);
		$stRollInfo = DB::name('student_schoolroll')->where('student_id',$st_id)->order('id desc')->select();
		$FinanceInfo = DB::name('account')->where(['s_role'=>0,'s_id'=>$st_id])->select();
		foreach($stRollInfo as $k => $v){
			$stRollInfo[$k]['roll_name'] = DB::name('roll_status_name')->where('id',$v['source'])->value('name');
		}
		foreach($FinanceInfo as $k => $v){
			$FinanceInfo[$k]['total'] = $v['tuition'] + $v['registration'] + $v['material_cost'] + $v['photo_collection'] + $v['total_amount'];
		}
		$Curriculum = DB::name('school_specialty')->where('pid',$stInfo[0]['major_id'])->select();
		$scoreList = $this->getScoreListByStid($stInfo[0]['id']);
		$this->assign([
			'stInfo' => $this->translateStudent($stInfo)[0],
			'rollInfo' => $stRollInfo,
			'FinanceInfo' => $FinanceInfo,
			'Curriculum' => $Curriculum,
			'scoreList' => $scoreList
		]);
		return $this->fetch();
	}

	/**
	 * [编辑学员信息]
	 */
	public function editSTInfo(){
		$param = input('post.');
		$param['birthday'] = strtotime($param['birthday']);
		$param['test_time'] = strtotime($param['test_time']);
		return $stInfo = $this->studentModel->editSTInfo($param);
	}
	/**
	 * [删除学员]
	 */
	public function delST(){
		$param = input('post.');
        $ids = explode(',',$param['ids']);
		return $this->studentModel->delST($ids);
	}


    /**
     * [学籍变更]
     */
    public function schoolRoll (){
		$st_id = input('get.st_id');
		$stInfo = DB::name('student')->where('id',$st_id)->find();
		if($this->request->isPost()){
			$param = input('post.');
			if($param['source'] == ''){
				return ['code'=>0,'msg'=>'请选择变动原因'];
			}
			if($param['school_roll'] == ''){
				return ['code'=>0,'msg'=>'请选择学籍状态'];
			}
			$param['student'] = DB::name('student')->where('id',$param['student_id'])->value('name');
			$param['create_time'] = time();
			if($param['abnormal'] == 1){
				$result = $this->validate($param,"SchoolRollValidate");
				if(true !== $result){
					return ['code'=>0,'msg'=>$result];
				}
			}
			$param['create_uid'] = session('id');
			try{
				DB::name('student_schoolroll')->insert($param);
				DB::name('student')->where('id',$param['student_id'])->update(['school_roll' => 1]);
				// 毕业
				if($param['school_roll'] == 2){
					DB::name('student')->where('id',$param['student_id'])->update(['school_roll' => 2]);
				}
				// 异常变动
				if($param['abnormal'] == 1){
					// 转校转出记录
					if($param['school_id'] != $param['to_school_id']){
						$roll_out_data = [
							'st_id' => $param['student_id'],
							'school_id' => $param['school_id'],
							'school_name' => $param['school'],
							'to_id' => $param['to_school_id'],
							'to_name' => $param['to_school'],
							'c_time' => time()
						];
						DB::name('st_roll_out')->insert($roll_out_data);
					}
					$data = [
						'batch' => $param['to_batch'],
						'major' => $param['to_major'],
						'major_id' => $param['to_major_id'],
						'school' => $param['to_school'],
						'school_id' => $param['to_school_id'],
						'roll_status' => 1,
					];
					// 休学
					if($param['school_roll'] == 3){
						$data['school_roll'] = 3;
					}
					// 退学
					if($param['school_roll'] == 4){
						$data['school_roll'] = 4;
					}
					DB::name('student')->where('id',$param['student_id'])->update($data);
					//插入流水
					if($param['money'] > 0){
						if($param['order_sn']==""){
							return ['code'=>0,'msg'=>'请选择单号'];
						}
						$orderInfo = DB::name('order')->where('order_sn',$param['order_sn'])->find();
						$payDate = DB::name('webset')->where('name','pay_date')->value('values');
						$finish_time = strtotime(date("Y-m-").$payDate);
						$FinData = [
							'order_sn' => $param['order_sn'],
							'm_id' => $orderInfo['m_id'],
							's_id' => $param['student_id'],
							's_role' => 0,
							'total_amount' => $param['money'],
							'status' => 0,
							'c_time' => time(),
							'finish_time' => $finish_time,
							'remarks' => $param['money_remark'],
							'source' => 4,
							'create_uid' => session('id'),
						];
						$accId = DB::name('account')->insertGetId($FinData);
						DB::name('account')->where('id',$accId)->update(['account_sn' => date("Ymd").$accId]);
					}
				}
				return ['code'=>1,'msg'=>'保存成功'];
			}catch(\Exception $e){
				return ['code'=>0,'msg'=>'保存失败:'.$e->getMessage()];
			}
		}
		$rollStatus = DB::name('roll_status_name')->order('id desc')->select();
		$this->assign([
			'stInfo' => $stInfo,
			'rollStatus' => $rollStatus,
		]);
		return $this->fetch();
    }
	/**
	 * [学籍变动时添加流水选择单号]
	 */
	public function getOrderSnByStId(){
		$param = input('post.');
		$m_id = DB::name('student')->where('id',$param['st_id'])->value('m_id');
		$orders = DB::name('order')->where('m_id',$m_id)->select();
		foreach($orders as $k => $v){
			$orders[$k]['c_time'] = date('Y-m-d H:i:s',$v['c_time']);
			$orders[$k]['grade_name'] = DB::name('product_attr')->where('id',$v['grade'])->value('name');
			$orders[$k]['edu'] = DB::name('product_attr')->where('id',$v['acquisition_mode'])->value('name');
		}
		return ['code'=>1,'data'=>$orders,'msg'=>''];
	}

	/**
	 * [安排考试时间]
	 */
	public function editTestTime(){
		$param = input('post.');
		$idArr = explode(",",$param['ids']);
		$test_time = strtotime($param['test_time']);
		return $this->studentModel->editTestTime($idArr,$test_time);
	}

	/**
	 * [批量升级、毕业]
	 */
	public function upGraduation(){
		$param = input('post.');
		$idArr = explode(",",$param['ids']);
		if($param['source'] == ""){
			return ['code' =>0 ,'msg' => '操作失败：请选择变动原因'];
		}
		if($param['school_roll'] == ""){
			return ['code' =>0 ,'msg' => '操作失败：请选择学籍状态'];
		}
		DB::startTrans();
		try{
			foreach ($idArr as $v) {
				$stInfo = DB::name('student')->where('id',$v)->find();
				$data = [
					'student_id' => $stInfo['id'],
					'student' => $stInfo['name'],
					'school' => $stInfo['school'],
					'school_id' =>$stInfo['school_id'],
					'major_id' => $stInfo['major_id'],
					'major' => $stInfo['major'],
					'batch' => $stInfo['batch'],
					'class' => $stInfo['class'],
					'create_time' => time(),
					'create_uid' => session('id'),
					'abnormal' => 0,
					'source' => $param['source'],
					'remark' => $param['remark'],
				];
				DB::name('student_schoolroll')->insert($data);
				if($param['school_roll'] == 2){
					DB::name('student')->where('id',$v)->update(['school_roll' => 2]);
				}
			}
			DB::commit();
			return ['code' =>1 ,'msg' => '操作成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code' =>0 ,'msg' => '操作失败:'.$e->getMessage()];
		}
	}

    /**
     * [报名列表]
     */
    public function enrolList (){
		if(request()->isAjax()){
            $param = input('param.');
			$param['seaName'] ? $whereName=['name'=>['like','%'.$param['seaName'].'%']] : $whereName = [];
			$param['seaPhone'] ? $wherePhone=['phone'=>['like','%'.$param['seaPhone'].'%']] : $wherePhone = [];
			$param['seaSchool'] ? $whereSchool=['school_id'=>$param['seaSchool']] : $whereSchool = [];
			$param['seaMajor'] ? $whereMajor=['major_id'=>$param['seaMajor']] : $whereMajor = [];
			$where = ['delete_status'=>0,'school_roll'=>0];
            $limit = $param['pageSize'];
            $offset = ($param['pageNumber'] - 1) * $limit;
            $return['rows'] = $this->studentModel->getInfoByWhere($where,$whereName,$wherePhone,$whereSchool,$whereMajor,'','',true,$offset,$limit);
            $return['total'] = $this->studentModel->getInfoByWhere($where,$whereName,$wherePhone,$whereSchool,$whereMajor,'','');
			$return['rows'] = $this->translateStudent($return['rows']);
            return $return;
        }
        $schools = DB::name('school_specialty')->where('pid',0)->select();
		$rollStatus = DB::name('roll_status_name')->where('is_abnormal',0)->order('id desc')->select();
        $this->assign([
            'schools' => $schools,
			'rollStatus' => $rollStatus,
        ]);
		$proModel = new ProductModel();
		$this->assign([
			'CanseeSchool' => $proModel->getCanseeSchool(),
		]);
        return $this->fetch();
    }

	/**
	 * [学员报名、分配批次]
	 * 1.更改 student school_roll,batch,school_date
	 * 2.插入一条数据至snake_student_schoolroll
	 */
	public function batchST(){
		$param = input('post.');
		$idArr = explode(",",$param['ids']);
		$param['batch'] = trim($param['batch']);
		// $param['class'] = trim($param['class']);
		if($param['source'] == ''){
			return ['code'=>0,'msg'=>'分配批次失败，报名失败：请选择变动原因'];
		}
		unset($param['ids']);
		DB::startTrans();
		try {
			foreach($idArr as $v){
				$stInfo = DB::name('student')->where('id',$v)->find();
				$rollData = [
					'student_id' => $v,
					'student' => $stInfo['name'],
					'school' => $stInfo['school'],
					'school_id' => $stInfo['school_id'],
					'major' => $stInfo['major'],
					'major_id' => $stInfo['major_id'],
					'batch' => $param['batch'],
					// 'class' => $param['class'],
					'create_time' => time(),
					'source' => $param['source'],
					'remark' => '分配批次报名入学',
					'create_uid' => session('id')
				];
				$roll_id = DB::name('student_schoolroll')->insert($rollData);
				DB::name('student')->where('id',$v)->update([
					'school_roll'=>1,
					'batch' => $param['batch'],
					// 'class' => $param['class'],
					'school_date' => time(),
				]);
			}
			DB::commit();
			return ['code'=>1,'msg'=>'分配批次成功，报名成功'];
		} catch (\Exception $e) {
			DB::rollback();
			return ['code'=>0,'msg'=>'分配批次失败，报名失败'.$e->getMessage()];
		}

	}



    private function replenishTeacherInfo($param){
        foreach($param as $k => $v){
            switch ($param[$k]['status']) {
                case '1':
                    $param[$k]['status_name']="<span style='color:#1ab394;'>在职</span>";break;
                case '2':
                    $param[$k]['status_name']="<span style='color:#1c84c6'>请假中</span>";break;
                case '3':
                    $param[$k]['status_name']="<span style='color:#ed5565;'>交接中</span>";break;
                case '4':
                    $param[$k]['status_name']="<span style='color:#ed5565;'>已离职</span>";break;
                case '5':
                    $param[$k]['status_name']="<span style='color:#1c84c6'>已退休</span>";break;
                case '6':
                    $param[$k]['status_name']="<span style='color:#ec971f'>其他</span>";break;
                default:
                    $param[$k]['status_name']="<span style='color:#1ab394;'>在职</span>";break;
            }
            if($param[$k]['user_id'] == 0){
                if(authCheck('user/useradd')){
                    // $param[$k]['user']="<a class='btn btn-primary btn-sm' href='/admin/user/useradd?staff_id={$v['id']}'>添加账号</a>";
					$param[$k]['user']="<a class='btn btn-primary btn-sm' href='".url('user/useradd')."?staff_id={$v['id']}'>添加账号</a>";
                }else{
                    $param[$k]['user']="";
                }
            }else{
                if(authCheck('education/delteacheruser')){
                    $param[$k]['user']="<a class='btn btn-danger btn-sm' href='javascript:delTeacherUser({$v['id']});'>清除账号</a>";
                }else{
                    $param[$k]['user']="";
                }
            }
        }
        return $param;
    }

    /**
     * [教务老师列表文本框搜索条件]
     */
    private function seaWhereOr($param){
        $this->teacherModel->where(function($query)use($param){
            if($param['searchText']){
                $query->whereOr(['name'=>["like","%".$param['searchText']."%"]]);
                $query->whereOr(['school_name'=>["like","%".$param['searchText']."%"]]);
            }
        });
    }
    /**
     * [教务老师列表联系方式搜索条件]
     */
    private function seaWhere($param){
        $this->teacherModel->where(function($query)use($param){
            if($param['seaContInfo']){
                $query->whereOr(['phone'=>["like","%".$param['seaContInfo']."%"]]);
                $query->whereOr(['tel'=>["like","%".$param['seaContInfo']."%"]]);
                $query->whereOr(['email'=>["like","%".$param['seaContInfo']."%"]]);
            }
        });
    }

	/**
	 * [翻译学校ID]
	 */
	private function translateSchool_id($param){
		$id_str = '';
		$name_str = '';
		foreach($param['school_id'] as $k => $v){
			$param['school_name'][$k] = Db::name('school_specialty')->where('id',$v)->value('name');
			$id_str .= $v.",";
			$name_str .= $param['school_name'][$k] . ",";
		}
		$id_str = mb_substr($id_str,0,mb_strlen($id_str)-1);
		$name_str = mb_substr($name_str,0,mb_strlen($name_str)-1);
		$param['school_id'] = $id_str;
		$param['school_name'] = $name_str;
		return $param;
	}

	/**
	 * [翻译学生信息]
	 */
	public function translateStudent($param){
		foreach($param as $k => $v){
			if($v['sex'] == 1){
				$param[$k]['sex_name'] = "男";
			}elseif($v['sex'] == 2){
				$param[$k]['sex_name'] = "女";
			}else{
				$param[$k]['sex_name'] = "保密";
			}
			switch ($v['school_roll']) {
				case '1':$param[$k]['school_roll_name'] = "<span class='span-primary'>在读</span>";break;
				case '2':$param[$k]['school_roll_name'] = "<span class='span-success'>已毕业</span>";break;
				case '3':$param[$k]['school_roll_name'] = "<span class='span-warning'>休学中</span>";break;
				case '4':$param[$k]['school_roll_name'] = "<span class='span-danger'>已退学</span>";break;
				default:$param[$k]['school_roll_name'] = "<span class='span-info'>报名中</span>";break;
			}
			if($v['roll_status'] == 0){
				$param[$k]['roll_status_name'] = "无";
			}else{
				$param[$k]['roll_status_name'] = "<span class='span-danger span-strong'>有</span>";
			}
			//订单信息
			$orderInfo = DB::name('order')->where([
				'm_id' => $v['m_id'],
				'school_id' => $v['school_id'],
				'major_id' => $v['major_id']
			])->find();
			$param[$k]['enroll_time'] = date("Y-m-d",$orderInfo['c_time']);
			$param[$k]['tuition'] = $orderInfo['tuition'];
			$param[$k]['registration'] = $orderInfo['registration'];
			$param[$k]['material_cost'] = $orderInfo['material_cost'];
			$param[$k]['photo_collection'] = $orderInfo['photo_collection'];

			//层次
			$param[$k]['grade'] = DB::name('product_attr')->where('id',$v['grade'])->value('name');

			// 所属咨询师
			$param[$k]['consultant_name'] = DB::name('user')->where('id',$v['consultant'])->value('real_name');
			$consultant_role = DB::name('user')->where('id',$v['consultant'])->value('role_id');
			$param[$k]['consultant_depart'] = DB::name('role')->where('id',$consultant_role)->value('department_id');
			$departModel = new DepartmentModel();
			// $param[$k]['consultant_department'] = DB::name('department')->where('id',$param[$k]['consultant_depart'])->value('name');
			$param[$k]['consultant_department'] = $departModel->getTotalDepartStr($param[$k]['consultant_depart']);
			// 时间
			if($v['birthday']){
				$param[$k]['birthday'] = date('Y-m-d',$v['birthday']);
			}
			if($param[$k]['test_time']){
				$param[$k]['test_time'] = date('Y-m-d H:i:s',$v['test_time']);
			}
			//操作按钮
			$stSchoolRollUrl = url("education/schoolRoll")."?st_id=".$v['id'];
			if($v['school_roll'] == 2  || $v['school_roll'] == 4){
				$param[$k]['operate'] = "";
			}else{
				$param[$k]['operate'] = "<a class='btn btn-sm btn-danger' href='".$stSchoolRollUrl."'>学籍变动</a>";
			}
			// memberInfo
			$memberInfo = DB::name('member')->where('id',$v['m_id'])->find();
			if(empty($memberInfo)){
				$memberInfo = [
					'address' => '-',
					'nation' => '-',
					'id_card' => '-',
					'birthday' => '-',
					'qq' => '-',
					'weixin' => '-',
					'education' => '-',
					'intention' => '-',
					'industry' => '-',
					'region' => '-',
					'native_place' => '-',
					'graduate_school' => '-',
					'certificate_number' => '-',
					'graduation_time' => '-',
					'source_origin' => '-1',
					'grade' => '-1',
					'remarks' => '-',
				];
			}
			$param[$k]['memInfo_address'] = $memberInfo['adress'];
			$param[$k]['memInfo_nation'] = $memberInfo['nation'];
			$param[$k]['memInfo_id_card'] = $memberInfo['id_card'];
			$param[$k]['memInfo_birthday'] = $memberInfo['birthday'];
			$param[$k]['memInfo_qq'] = $memberInfo['qq'];
			$param[$k]['memInfo_weixin'] = $memberInfo['weixin'];
			$param[$k]['memInfo_education'] = $memberInfo['education'];
			$param[$k]['memInfo_intention'] = $memberInfo['intention'];
			$param[$k]['memInfo_industry'] = $memberInfo['industry'];
			$param[$k]['memInfo_region'] = $memberInfo['region'];
			$param[$k]['memInfo_native_place'] = $memberInfo['native_place'];
			$param[$k]['memInfo_graduate_school'] = $memberInfo['graduate_school'];
			$param[$k]['memInfo_certificate_number'] = $memberInfo['certificate_number'];
			$param[$k]['memInfo_graduation_time'] = $memberInfo['graduation_time'];
			$param[$k]['memInfo_source_origin'] = DB::name('member_attr')->where('id',$memberInfo['source_origin'])->value('name');
			$param[$k]['memInfo_grade'] = DB::name('member_attr')->where('id',$memberInfo['grade'])->value('name');
			$param[$k]['memInfo_remarks'] = $memberInfo['remarks'];
		}
		return $param;
	}

	/**
	 * [设置学籍状态名称]
	 */
	public function roll_status(){
		$rollStatus = DB::name('roll_status_name')->order('id desc')->select();
		$this->assign([
			'rollStatus' => $rollStatus
		]);
		return $this->fetch();
	}

	/**
	 * [编辑学籍状态名称]
	 */
	public function editRollStatus(){
		$param = input('post.');
		if(isset($param['name'])){
			if(!$param['name']){
				return ['code'=>0,'msg'=>'名称不能为空'];
			}
		}
		$result = DB::name('roll_status_name')->where('id',$param['id'])->update($param);
		if($result === false){
			return ['code'=>0,'msg'=>'编辑失败'];
		}else{
			return ['code'=>1,'msg'=>'编辑成功'];
		}
	}

	/**
	 * [删除学籍状态名称]
	 */
	public function delRollStatus(){
		$param = input('post.');
		$result = DB::name('roll_status_name')->where('id',$param['id'])->delete();
		if($result === false){
			return ['code'=>0,'msg'=>'删除失败'];
		}else{
			return ['code'=>1,'msg'=>'删除成功'];
		}
	}

	/**
	 * [添加学籍状态名称]
	 */
	public function addRollStatus(){
		$param = input('post.');
		if(!$param['name']){
			return ['code'=>0,'msg'=>'名称不能为空'];
		}
		$result = DB::name('roll_status_name')->insert($param);
		if($result === false){
			return ['code'=>0,'msg'=>'添加失败'];
		}else{
			return ['code'=>1,'msg'=>'添加成功'];
		}
	}

	/**
	 * [教务统计]
	 */
	public function statistics(){
		if($this->request->isPost()){
			$school_ids = DB::name('teacher')->where('user_id',input('post.adminId'))->value('school_id');
		}else{
			$school_ids = DB::name('teacher')->where('user_id',session('id'))->value('school_id');
		}
		if($school_ids != ''){
			$schoolIdArr = explode(",",$school_ids);
			foreach($schoolIdArr as $k => $v){
				$majorIds[$k] = DB::name('school_specialty')->where('pid',$v)->field('pid,id')->select();
			}
			$departModel = new DepartmentModel();
			$majorIds = $departModel->ChangeArrayDimension($majorIds);
		}else{
			$majorIds = DB::name('school_specialty')->where(['pid'=>['<>',0]])->field('pid,id')->order('pid asc')->select();
			$schoolIdArr = DB::name('school_specialty')->where('pid',0)->column('id');
		}
		$stModel = new StudentModel();
		foreach($majorIds as $k => $v){
			$majorIds[$k]['school_name'] = DB::name('school_specialty')->where('id',$v['pid'])->value('name');
			$majorIds[$k]['major_name'] = DB::name('school_specialty')->where('id',$v['id'])->value('name');
			#真数据
			$majorIds[$k]['majorSt_a'] = $stModel->getInfoByWhere(['major_id'=>$v['id']]);//总数
			$majorIds[$k]['majorSt_b'] = $stModel->getInfoByWhere(['major_id'=>$v['id'],'school_roll'=>0]);//报名中
			$majorIds[$k]['majorSt_c'] = $stModel->getInfoByWhere(['major_id'=>$v['id'],'school_roll'=>1]);//在读
			$majorIds[$k]['majorSt_d'] = $stModel->getInfoByWhere(['major_id'=>$v['id'],'school_roll'=>2]);//毕业
			$majorIds[$k]['majorSt_cd'] = $majorIds[$k]['majorSt_c'] + $majorIds[$k]['majorSt_d'];//正常
			$majorIds[$k]['majorSt_e'] = $stModel->getInfoByWhere(['major_id'=>$v['id'],'school_roll'=>3]);//休学
			$majorIds[$k]['majorSt_f'] = $stModel->getInfoByWhere(['major_id'=>$v['id'],'school_roll'=>4]);//退学
			$majorIds[$k]['majorSt_ef'] = $majorIds[$k]['majorSt_e'] + $majorIds[$k]['majorSt_f'];//异常

			/*
			#假数据
			$majorIds[$k]['majorSt_a'] = rand(1,6666);
			$majorIds[$k]['majorSt_b'] = rand(1,6666);
			$majorIds[$k]['majorSt_c'] = rand(1,6666);
			$majorIds[$k]['majorSt_d'] = rand(1,6666);
			$majorIds[$k]['majorSt_cd'] = $majorIds[$k]['majorSt_c'] + $majorIds[$k]['majorSt_d'];
			$majorIds[$k]['majorSt_e'] = rand(1,60);
			$majorIds[$k]['majorSt_f'] = rand(1,60);
			$majorIds[$k]['majorSt_ef'] = $majorIds[$k]['majorSt_e'] + $majorIds[$k]['majorSt_f'];
			*/
		}


		#真数据
		$totalSt['a'] = $stModel->getInfoByWhere();
		$totalSt['b'] = $stModel->getInfoByWhere(["school_roll"=>0]);
		$totalSt['c'] = $stModel->getInfoByWhere(["school_roll"=>1]);
		$totalSt['d'] = $stModel->getInfoByWhere(["school_roll"=>2]);
		$totalSt['cd'] = $totalSt['c'] + $totalSt['d'];
		$totalSt['e'] = $stModel->getInfoByWhere(["school_roll"=>3]);
		$totalSt['f'] = $stModel->getInfoByWhere(["school_roll"=>4]);
		$totalSt['ef'] = $totalSt['e'] + $totalSt['f'];

		/*
		#假数据
		$totalSt['a'] = rand(1,6666);
		$totalSt['b'] = rand(1,6666);
		$totalSt['c'] = rand(1,6666);
		$totalSt['d'] = rand(1,6666);
		$totalSt['e'] = rand(1,60);
		$totalSt['f'] = rand(1,60);
		$totalSt['ef'] = $totalSt['e'] + $totalSt['f'];
		$totalSt['cd'] = $totalSt['c'] + $totalSt['d'];
		*/

		if($this->request->isPost()){
			$Xdata = [];
			foreach($majorIds as $k => $v){
				$Xdata[$k] = $v['school_name']."-".$v['major_name'];
				$Ydata['Bdata'][$k] = $v['majorSt_b'];
				$Ydata['Cdata'][$k] = $v['majorSt_c'];
				$Ydata['Ddata'][$k] = $v['majorSt_d'];
				$Ydata['CDdata'][$k] = $v['majorSt_cd'];
				$Ydata['Edata'][$k] = $v['majorSt_e'];
				$Ydata['Fdata'][$k] = $v['majorSt_f'];
				$Ydata['EFdata'][$k] = $v['majorSt_ef'];
			}
			foreach($schoolIdArr as $ke => $vo){
				$schoolXdata[$ke] = DB::name('school_specialty')->where('id',$vo)->value('name');

				#真数据
				$schoolYdata['Bdata'][$ke] = $stModel->getInfoByWhere(['school_id'=>$vo,'school_roll'=>0]);//报名中
				$schoolYdata['Cdata'][$ke] = $stModel->getInfoByWhere(['school_id'=>$vo,'school_roll'=>1]);//在读
				$schoolYdata['Ddata'][$ke] = $stModel->getInfoByWhere(['school_id'=>$vo,'school_roll'=>2]);//毕业
				$schoolYdata['CDdata'][$ke] = $schoolYdata['Cdata'][$ke] + $schoolYdata['Ddata'][$ke];//正常
				$schoolYdata['Edata'][$ke] = $stModel->getInfoByWhere(['school_id'=>$vo,'school_roll'=>3]);//休学
				$schoolYdata['Fdata'][$ke] = $stModel->getInfoByWhere(['school_id'=>$vo,'school_roll'=>4]);//退学
				$schoolYdata['EFdata'][$ke] = $schoolYdata['Edata'][$ke] + $schoolYdata['Fdata'][$ke];//异常

				/*
				#假数据
				$schoolYdata['Bdata'][$ke] = rand(1,5135);
				$schoolYdata['Cdata'][$ke] = rand(1,5135);
				$schoolYdata['Ddata'][$ke] = rand(1,5135);
				$schoolYdata['CDdata'][$ke] = $schoolYdata['Cdata'][$ke] + $schoolYdata['Ddata'][$ke];
				$schoolYdata['Edata'][$ke] = rand(1,60);
				$schoolYdata['Fdata'][$ke] = rand(1,60);
				$schoolYdata['EFdata'][$ke] = $schoolYdata['Edata'][$ke] + $schoolYdata['Fdata'][$ke];
				*/
			}
			return ['code'=>1,'msg'=>'','Xdata'=>$Xdata,'Ydata'=>$Ydata,'schoolXdata'=>$schoolXdata,'schoolYdata'=>$schoolYdata];
		}else{
			$this->assign([
				'iTitle' => $majorIds,
				'totalSt' => $totalSt,
				'adminId' => session('id')
			]);
			return $this->fetch();
		}
	}

	/**
	 * [导出全部教务统计表格]
	 */
	public function ExpotrAllEduInfo(){
		$StModel = new StudentModel();
		$res = $StModel->getAllStInfoNoPage();
		$res = $this->translateStudent($res);
		$data = [];
		foreach($res as $k => $v){
			$data[$k]['id'] = $v['id'];
			$data[$k]['name'] = $v['name'];
			$data[$k]['enroll_time'] = $v['enroll_time'];
			$data[$k]['school'] = $v['school'];
			$data[$k]['grade'] = $v['grade'];
			$data[$k]['major'] = $v['major'];
			$data[$k]['grade'] = $v['grade'];
			$data[$k]['batch'] = $v['batch'];
			$data[$k]['phone'] = $v['phone'];
			$data[$k]['sex_name'] = $v['sex_name'];
			$data[$k]['consultant_name'] = $v['consultant_name'];
			$data[$k]['consultant_department'] = $v['consultant_department'];

			$data[$k]['memInfo_address'] = $v['memInfo_address'];
			$data[$k]['memInfo_nation'] = $v['memInfo_nation'];
			$data[$k]['memInfo_id_card'] = $v['memInfo_id_card'];
			$data[$k]['memInfo_birthday'] = $v['memInfo_birthday'];
			$data[$k]['memInfo_qq'] = $v['memInfo_qq'];
			$data[$k]['memInfo_weixin'] = $v['memInfo_weixin'];
			$data[$k]['memInfo_education'] = $v['memInfo_education'];
			$data[$k]['memInfo_intention'] = $v['memInfo_intention'];
			$data[$k]['memInfo_industry'] = $v['memInfo_industry'];
			$data[$k]['memInfo_region'] = $v['memInfo_region'];
			$data[$k]['memInfo_native_place'] = $v['memInfo_native_place'];
			$data[$k]['memInfo_graduate_school'] = $v['memInfo_graduate_school'];
			$data[$k]['memInfo_certificate_number'] = $v['memInfo_certificate_number'];
			$data[$k]['memInfo_graduation_time'] = $v['memInfo_graduation_time'];
			$data[$k]['memInfo_source_origin'] = $v['memInfo_source_origin'];
			$data[$k]['memInfo_grade'] = $v['memInfo_grade'];
			$data[$k]['memInfo_remarks'] = $v['memInfo_remarks'];

			$data[$k]['tuition'] = $v['tuition'];
			$data[$k]['registration'] = $v['registration'];
			$data[$k]['material_cost'] = $v['material_cost'];
			$data[$k]['photo_collection'] = $v['photo_collection'];
		}
		foreach($res as $k => $v){
			if($v['roll_status'] == 0){
				$data[$k]['roll_status_name'] = '无';
			}else{
				$data[$k]['roll_status_name'] = '有';
			}
			switch ($v['school_roll']) {
				case '0':
					$data[$k]['school_roll_name'] = '报名中';
					break;
				case '1':
					$data[$k]['school_roll_name'] = '在读';
					break;
				case '2':
					$data[$k]['school_roll_name'] = '毕业';
					break;
				case '3':
					$data[$k]['school_roll_name'] = '休学';
					break;
				case '4':
					$data[$k]['school_roll_name'] = '退学';
					break;
				default:
					$data[$k]['school_roll_name'] = '在读';
					break;
			}
		}
		$savePath = explode('../application/',APP_PATH)[0].'upload/excel/';
		$title = [
			'ID','学员姓名','报名时间','学校','层次','专业','批次','手机','性别','咨询师',
			'咨询师部门','地址','民族','身份证号','生日','QQ','微信','学历','意向专业','工作行业',
			'所在地区','籍贯','毕业学校','证书编号','毕业时间','生源途径','等级','备注',
			'学费','报名费','资料费','照片采集费','有无异常变动','学籍状态'
		];
		$FinCtrl = new Finance();
		$FinCtrl->exportExcel($title,$data, 'downloadEdu', $savePath, false);
	}

	/**
	 * [保存学生成绩]
	 */
	public function saveScore(){
		$param = input('post.');
		$st_id = $param['st_id'];
		$st_name = $param['st_name'];
		$term = $param['term'];

		$check = DB::name('student_score')->where([
			'st_id' => $st_id,
			'term' => $term
		])->find();

		if(!empty($check)){
			return ['code'=>0,'msg'=>'该生该学期的成绩已经录入，不能重复录入'];
		}

		unset($param['st_id']);
		unset($param['st_name']);
		unset($param['term']);

		$curriculum_ids = [];
		foreach($param as $k => $v){
			$curriculum_ids[] = explode('_',$k)[1];
		}
		$curriculum_ids = array_merge(array_unique($curriculum_ids));
		if(empty($curriculum_ids)){
			return ['code'=>0,'msg'=>'请选择课程添加成绩'];
		}
		DB::startTrans();
		try{
			foreach($curriculum_ids as $v){
				$data = [
					'st_id' => $st_id,
					'st_name' => $st_name,
					'term' => $term,
					'curriculum_id' => $v,
					'curriculum_name' => DB::name('school_specialty')->where('id',$v)->value('name'),
					'scoreNormal' => $param['scoreNormal_'.$v],
					'scoreExam' => $param['scoreExam_'.$v],
					'scoreFinal' => $param['scoreFinal_'.$v]
				];
				DB::name('student_score')->insert($data);
			}
			DB::commit();
			return ['code'=>1,'msg'=>'添加成功'];
		}catch(\Exception $e){
			DB::rollback();
			return ['code'=>0,'msg'=>'添加失败,'.$e->getMessage()];
		}
	}

	/**
	 * [获取学员成绩By学员ID]
	 */
	public function getScoreListByStid($id){
		$res = [];
		for($i=1;$i<11;$i++){
			$res[$i] = DB::name("student_score")->where(['st_id' => $id,'term' => $i])->select();
		}
		return $res;
	}

	/**
	 * [修改学生成绩单]
	 */
	public function saveScoreChange(){
		$param = input('post.');
		$res = DB::name("student_score")->where('id',$param['id'])->update($param);
		if($res === false){
			return ['code'=>0,'msg'=>'保存失败请稍后再试'];
		}else{
			return ['code'=>1,'msg'=>'保存成功'];
		}
	}
}
